package com.bluezone.dec.utils;

import com.bluezone.dec.common.SystemConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author HHL
 * @description 时间转换工具类
 * @date 2018/9/29 - 12:01
 */
public class TimeTransferUtils {

    private static Logger log = LoggerFactory.getLogger(TimeTransferUtils.class);

    private TimeTransferUtils() {
    }

    /* 获取系统当前年份 */
    public static String getSystemCurrentYear() {

        Calendar date = Calendar.getInstance();
        return String.valueOf(date.get(Calendar.YEAR));
    }

    /* 将时间字符串转为日期类型 */
    public static Date string2Date(String dateStr) {

        Date date = null;
        SimpleDateFormat sf = null;

        /* 获得一个时间格式的字符串 */
        int blankIndex = dateStr.trim().indexOf(" '  '");

        if (blankIndex != -1) {
            /* 获得SimpleDateFormat类，我们转换为yyyy-MM-dd HH:mm:ss的时间格式 */
            sf = new SimpleDateFormat(SystemConstant.LONG_DATA_FORMATE);
        } else {
            sf = new SimpleDateFormat("yyyy-MM-dd");
        }

        try {
            /* 使用SimpleDateFormat的parse()方法生成Date */
            date = sf.parse(dateStr);
        } catch (ParseException e) {
            log.warn("时间字符串转为日期类型转换失败", e);
        }
        return date;
    }

    /* 将Date类型转为String类型 */
    public static String date2String(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(SystemConstant.LONG_DATA_FORMATE);
        return sdf.format(date);
    }

    /**
     * 获取最近一年来的时期
     *
     * @return
     */
    public static List<String> getDayList() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        List<String> dateList = new ArrayList<>();
        // 获取结束时间为当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        try {
            Date end = dateFormat.parse(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1));
            /*获取开始时间为一年前的下一个月*/
            calendar.add(Calendar.YEAR, -1);
            calendar.add(Calendar.MONTH, +1);
            Date begin = dateFormat.parse(calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1));
            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();
            min.setTime(begin);
            min.set(Calendar.DAY_OF_MONTH, 1);
            max.setTime(end);
            max.set(Calendar.DAY_OF_MONTH, 2);
            while (min.before(max)) {
                dateList.add(dateFormat.format(min.getTime()));
                min.add(Calendar.MONTH, 1);
            }
        } catch (ParseException e) {
            log.error("日期转换失败", e);
        }
        return dateList;
    }
}
